/**
 * This is a API server
 */

import express, { type Request, type Response, type NextFunction }  from 'express';
import cors from 'cors';
import path from 'path';
import dotenv from 'dotenv';
import { fileURLToPath } from 'url';
import authRoutes from './routes/auth.js';
import aiRoutes from './routes/ai.js';
import gitRoutes from './routes/git.js';
import projectsRoutes from './routes/projects.js';
import configRoutes from './routes/config.js';
import debugRoutes from './routes/debug.js';
import dockerRoutes from './routes/docker.js';
import pathMappingRoutes from './routes/pathMapping.js';
import { initDatabase } from './config/database.js';

// for esm mode
const __filename = fileURLToPath(import.meta.url);
const __dirname = path.dirname(__filename);

// load env
const envPath = path.join(__dirname, '..', '.env');
console.log('🔍 Loading .env from:', envPath);
const result = dotenv.config({ path: envPath });
if (result.error) {
  console.log('❌ .env loading error:', result.error);
} else {
  console.log('✅ .env loaded successfully');
  console.log('🔍 DB_HOST from env:', process.env.DB_HOST);
}

// 初始化数据库连接
initDatabase().catch(error => {
  console.log('数据库初始化失败，将使用文件存储:', error.message);
});

const app: express.Application = express();

app.use(cors());
app.use(express.json({ limit: '10mb' }));
app.use(express.urlencoded({ extended: true, limit: '10mb' }));

/**
 * API Routes
 */
app.use('/api/auth', authRoutes);
app.use('/api/ai', aiRoutes);
app.use('/api/git', gitRoutes);
app.use('/api/projects', projectsRoutes);
app.use('/api/config', configRoutes);
app.use('/api/debug', debugRoutes);
app.use('/api/docker', dockerRoutes);
app.use('/api/path-mapping', pathMappingRoutes);

/**
 * health
 */
app.use('/api/health', (req: Request, res: Response, next: NextFunction): void => {
  res.status(200).json({
    success: true,
    message: 'ok'
  });
});

/**
 * error handler middleware
 */
app.use((error: Error, req: Request, res: Response, next: NextFunction) => {
  res.status(500).json({
    success: false,
    error: 'Server internal error'
  });
});

/**
 * 404 handler
 */
app.use((req: Request, res: Response) => {
  res.status(404).json({
    success: false,
    error: 'API not found'
  });
});

export default app;